package com.example.administrator.testapp;

import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.AnReaderDemo.EPCInfo;
import com.example.AnReaderDemo.bean.LabelLackBean;
import com.example.AnReaderDemo.bean.LabelStrength;
import com.example.AnReaderDemo.bean.ScanStatementBean;
import com.example.cabinetcontrol.CabinetClass;
import com.example.cabinetcontrol.ILockControl;
import com.example.cabinetcontrol.util.ILockCallBack;
import com.example.cabinetcontrol.util.TimeUtils;
import com.example.presenter.ILabelCallBack;
import com.example.presenter.config.RFID_Config;
import com.example.presenter.label.IScanLabel;
import com.example.presenter.label.ScanLebelClass;
import com.rfid.api.ADReaderInterface;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2019/9/19 0019.
 */

public class TestActivity extends AppCompatActivity implements ILabelCallBack,ILockCallBack {

    Button test_toScan_Bt;
    Button test_stop_Bt;
    Button test_Connect_Bt;
    Button test_Close_Bt;
    Button test_Seting_Bt;
    Button clearScanList_Bt;

    TextView test_LabelMsg_Tv;//显示标签盘点内容
    TextView doorStatus_Tv;//门状态
    TextView table_Tv;//标题栏

    Button openDoor_Bt;
    Button chectDoor_Bt;
    Button chectTemperature_Bt;

    ILockControl iLockControl;//锁板控制类
    public static IScanLabel iScanLabel;//标签控制类

    RFID_Config rfid_config;//RFID配置

    private TextView Msg_Tv;
    private CheckBox isCircula_CB;//循环
    private Button memory_status_Bt;//内存状态
    private Button clearRecord_Bt;//清除记录
    private ListView scanStatement_Lv;//盘点累积个数显
    private ListView labelStrength_Lv;//盘点强度弱次数显示
    private ListView labelLack_Lv;//缺少次数显示
    private int scanCount = 0;//盘点次数
    private int intervalTime = 5000;//盘点间隔

    //盘点累积个数显示
    List<ScanStatementBean> scanStatementBeans = new ArrayList<ScanStatementBean>();
    ArrayAdapter<ScanStatementBean> adapter;


    //标签信号强度数据
    List<LabelStrength> labelStrengths = new ArrayList<>();
    ArrayAdapter<LabelStrength> labelStrengthAdapter;

    //缺少标签次数
    private List<LabelLackBean> lackBeanList = new ArrayList<>();
    ArrayAdapter<LabelLackBean> labelLackAdapter;

    //以第一次盘点个数为基准的标签数据数列
    private List<String> Labels = new ArrayList<String>();
    private List<EPCInfo> epcInfoList = new ArrayList<>();//第一次保存所有参数的数列

    ActivityManager activityManager;//查询内存消耗
    ActivityManager.MemoryInfo memInfo;

    final static private int HANDLER_MSG_VIEW_EMPTY = 0;//清除日志Text
    final static private int HANDLER_MSG_TEXT_VIEW = 1;//增加日志显示数据

    final int msgSum = 200;//显示日志条数容量
    String [] msgArray = new String[msgSum];
    int msgOrder = 0;

    boolean circulate = false;//循环
    boolean isScan = false;//是否盘点中
    boolean isRun = true;//程序是否在运行中
    boolean isConnect = false;//与RFID的连接状态


    public Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case HANDLER_MSG_VIEW_EMPTY:
                    msgOrder = 0;
                    Msg_Tv.setText("");
                    break;
                case HANDLER_MSG_TEXT_VIEW:
                    try {
                        String data = msg.getData().getString("msg");
                        if (msgOrder >= msgSum) {
                            for (int i = 0; i <msgSum-1; i++) {
                                msgArray[i] = msgArray[i+1];
                            }
                            msgOrder = msgSum - 1;
                        }
                        msgArray[msgOrder] = data;
                        msgOrder++;

                        String str = "";
                        for (int i = 0; i < msgOrder; i++) {
                            str = str + i + "、" + msgArray[i] + "\n";
                        }
                        Msg_Tv.setText(str);
                    }
                    catch (Exception e ){
                        Toast.makeText(getApplicationContext(),"显示发送错误："+e,Toast.LENGTH_SHORT).show();
                    }
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    public void setShowMsg(String msg) {
        Message message = new Message();
        Bundle bundle = new Bundle();
        bundle.putString("msg",msg+"\n"+ TimeUtils.getTime());
        message.setData(bundle);
        message.what = 1;
        handler.sendMessage(message);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //取消系统时间状态栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.test_activity);

        test_toScan_Bt = (Button)findViewById(R.id.test_toScan_Bt);
        test_stop_Bt = (Button)findViewById(R.id.test_stop_Bt);
        test_Connect_Bt = (Button)findViewById(R.id.test_Connect_Bt);
        test_Close_Bt = (Button)findViewById(R.id.test_Close_Bt);
        test_Seting_Bt = (Button)findViewById(R.id.test_Seting_Bt);
        clearScanList_Bt = (Button)findViewById(R.id.clearScanList_Bt);

        openDoor_Bt = (Button)findViewById(R.id.openDoor_Bt);
        chectDoor_Bt = (Button)findViewById(R.id.chectDoor_Bt);
        chectTemperature_Bt = (Button)findViewById(R.id.chectTemperature_Bt);

        test_LabelMsg_Tv = (TextView)findViewById(R.id.test_msg_Tv);
        doorStatus_Tv = (TextView)findViewById(R.id.doorStatus_Tv);
        table_Tv = (TextView)findViewById(R.id.table_Tv);

        rfid_config = new RFID_Config(this);

        PackageManager pm = getPackageManager();
        //获取包信息
        try {
            PackageInfo packageInfo = pm.getPackageInfo(getPackageName(), 0);
            table_Tv.setText(packageInfo.versionName+"");
        } catch (PackageManager.NameNotFoundException e) {
            Log.d("Context","setTitle error:"+e);
        }

        String m_comList[] = ADReaderInterface.GetSerialPortPath();

        for (int i=0;i<m_comList.length;i++){
            setShowMsg("串口："+m_comList[i]);
            if (m_comList[i].equals("/dev/ttyS1")){
                iScanLabel = new ScanLebelClass(getApplicationContext(), this, rfid_config);
            }

            if (m_comList[i].equals("/dev/ttyS3")){
                iLockControl = new CabinetClass(getApplicationContext(),this);
            }
        }

        Msg_Tv = (TextView)findViewById(R.id.Msg_Tv);
        isCircula_CB = (CheckBox)findViewById(R.id.isCircula_CB);
        memory_status_Bt = (Button)findViewById(R.id.memory_status_Bt);
        clearRecord_Bt = (Button)findViewById(R.id.clearRecord_Bt);

        scanStatement_Lv = (ListView) findViewById(R.id.scanStatement_Lv);
        adapter = new ArrayAdapter<ScanStatementBean>(this,android.R.layout.simple_list_item_1,scanStatementBeans);
        scanStatement_Lv.setAdapter(adapter);

        labelStrength_Lv = (ListView) findViewById(R.id.labelStrength_Lv);
        labelStrengthAdapter = new ArrayAdapter<LabelStrength>(this,android.R.layout.simple_list_item_1,labelStrengths);
        labelStrength_Lv.setAdapter(labelStrengthAdapter);

        //缺少标签次数
        labelLack_Lv = (ListView) findViewById(R.id.labelLack_Lv);
        labelLackAdapter = new ArrayAdapter<LabelLackBean>(this,android.R.layout.simple_list_item_1,lackBeanList);
        labelLack_Lv.setAdapter(labelLackAdapter);

        activityManager=(ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        memInfo=new ActivityManager.MemoryInfo();
        activityManager.getMemoryInfo(memInfo);

        //循环
        isCircula_CB.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                circulate = isChecked;
            }
        });

        //查询内存使用
        memory_status_Bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Float maxMemory = Runtime.getRuntime().maxMemory()*1.0f/(1024*1024);
                Float totalMemory = Runtime.getRuntime().totalMemory()*1.0f/(1024*1024);
                Float freeMemory = Runtime.getRuntime().freeMemory()*1.0f/(1024*1024);
                Float SumMemory = totalMemory + freeMemory;
                setShowMsg("内存最大:"+maxMemory+"已用:"+totalMemory+",还剩:"+freeMemory+"，分配:"+SumMemory);
            }
        });

        clearRecord_Bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                handler.sendEmptyMessage(HANDLER_MSG_VIEW_EMPTY);
            }
        });

        //连接RFID设备
        test_Connect_Bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                OpenDev();
            }
        });

        //关闭RFID设备
        test_Close_Bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CloseDev();
            }
        });

        //盘点
        test_toScan_Bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toScanLabel();
            }
        });

        //停止盘点
        test_stop_Bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                stopScan();
                isCircula_CB.setChecked(false);
            }
        });

        //设置
        test_Seting_Bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (iScanLabel!=null && isConnect) {
                    Intent intent = new Intent(TestActivity.this, AdminActivity.class);
                    startActivityForResult(intent, 1);
                }
                else{
                    Toast.makeText(getApplicationContext(),"请先连接设备！",Toast.LENGTH_SHORT).show();
                }
            }
        });

        //开启柜锁
        openDoor_Bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (iLockControl!=null) {
                    iLockControl.openDoor();
                }
                else{
                    Toast.makeText(getApplicationContext(),"串口未能通讯",Toast.LENGTH_SHORT);
                }
            }
        });

        //查询柜锁
        chectDoor_Bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (iLockControl!=null) {
                    iLockControl.getDoorStatus();
                }
                else{
                    Toast.makeText(getApplicationContext(),"串口未能通讯",Toast.LENGTH_SHORT);
                }
            }
        });

        //查询温感
        chectTemperature_Bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (iLockControl!=null) {
                    iLockControl.getTemperature();
                }
                else{
                    Toast.makeText(getApplicationContext(),"串口未能通讯",Toast.LENGTH_SHORT);
                }
            }
        });

        //清除盘点记录数列
        clearScanList_Bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Labels = new ArrayList<>();
                epcInfoList = new ArrayList<>();
                scanStatementBeans.clear();
                adapter.notifyDataSetChanged();

                labelStrengths.clear();
                labelStrengthAdapter.notifyDataSetChanged();

                lackBeanList.clear();
                labelLackAdapter.notifyDataSetChanged();

                scanCount = 0;
            }
        });

    }

    //连接设备
    private void OpenDev(){
        if (iScanLabel!=null) {
            String comName = "/dev/ttyS1";//串口地址
            int iDevIPorBaud = 115200;//波特率
            String comType = "COM";//类型

            if(iScanLabel.OpenDev(comName, iDevIPorBaud, comType)){
                test_Connect_Bt.setEnabled(false);
                test_Close_Bt.setEnabled(true);
                isConnect = true;
                Toast.makeText(getApplicationContext(),"设备已成功连接", Toast.LENGTH_SHORT).show();
            }
            else {
                Toast.makeText(getApplicationContext(),"设备未成功连接", Toast.LENGTH_SHORT).show();
            }
        }
    }

    //关闭设备
    private void CloseDev(){
        if (iScanLabel!=null) {
            if (iScanLabel.CloseDev()) {
                stopScan();
                isCircula_CB.setChecked(false);

                test_Connect_Bt.setEnabled(true);
                test_Close_Bt.setEnabled(false);
                isConnect = false;
                Toast.makeText(getApplicationContext(),"设备已关闭连接", Toast.LENGTH_SHORT).show();
            }
            else {
                Toast.makeText(getApplicationContext(),"设备未能关闭连接", Toast.LENGTH_SHORT).show();
            }
        }
    }

    //盘点
    private void toScanLabel(){
        if (iScanLabel!=null && isConnect) {
            isScan = true;
            iScanLabel.toScanLabel();
            test_stop_Bt.setEnabled(true);
            test_toScan_Bt.setEnabled(false);
        }
        else {
            Toast.makeText(getApplicationContext(),"请先连接设备！",Toast.LENGTH_SHORT).show();
        }
    }

    //停止盘点
    private void stopScan(){
        if (iScanLabel!=null) {
            isScan = false;
            iScanLabel.stopScan();
            test_stop_Bt.setEnabled(false);
            test_toScan_Bt.setEnabled(true);
        }
    }

    //盘点数据的对比
    public void setLabelData(int size, List<String> list, List<EPCInfo> dataTmp) {
        try {
            if (Labels == null || Labels.size() == 0) {
                Labels.addAll(list);
            }

            if (epcInfoList == null || epcInfoList.size() == 0){
                epcInfoList.addAll(dataTmp);
            }

            List<String> lacks = new ArrayList<String>();
            lacks.addAll(Labels);

            //标签数相等
            if (size==Labels.size()){
                list.removeAll(Labels);
                int list_size = list.size();
                //不同标签
                if (list_size>0){
                    StringBuilder str = new StringBuilder();
                    for (int i=0;i<list_size;i++){
                        str.append(list.get(i)+"");
                    }
                    setShowMsg("不同标签："+str);
                }
            }
			else if (size != Labels.size()) {
                //缺少标签
                if (size<Labels.size()){
                    lacks.removeAll(list);
                    int lacks_size = lacks.size();
                    String EPC="";
                    int epcInfoList_szie = epcInfoList.size();

                    //存在的群少标签的个数
                    int lackSize = lackBeanList.size();
                    try {
                        StringBuilder str = new StringBuilder();
                        for (int i = 0; i < lacks_size; i++) {
                            for (int j = 0; j < epcInfoList_szie; j++) {
                                EPC = epcInfoList.get(j).getstrEpc();
                                if (EPC.equals(lacks.get(i).toString())) {
                                    str.append(EPC)
                                            .append("  初始位置强度：" + epcInfoList.get(j).getstr6())
                                            .append("\n");

                                    //增加缺少标签的显示数据
                                    boolean isExist=false;
                                    int lackCount;
                                    for (int lack=0;lack<lackSize;lack++){
                                        if (lackBeanList.get(lack).getLabel().equals(EPC)){
                                            lackCount = lackBeanList.get(lack).getCount();
                                            lackBeanList.get(lack).setCount(lackCount+1);
                                            isExist = true;
                                            break;
                                        }
                                    }
                                    if (!isExist) {
                                        lackBeanList.add(new LabelLackBean(EPC, 1));
                                    }

                                    break;
                                }
                            }
                        }
                        labelLackAdapter.notifyDataSetChanged();
                        setShowMsg("缺少标签：" + str);
                    }
                    catch (Exception e){
                        setShowMsg("输出缺少标签 error:"+e);
                    }
                }
                //多余标签
                else{
                    list.removeAll(lacks);
                    int list_size = list.size();
                    StringBuilder str = new StringBuilder();
                    EPCInfo epcInfo;
                    for (int i = 0; i < list_size; i++) {
                        for (int j=0;j<size;j++){
                            if (dataTmp.get(j).getstrEpc().trim().equals(list.get(i).trim())){
                                epcInfo = dataTmp.get(j);
                                str.append(epcInfo.getstrEpc() + "  天线："+epcInfo.getstr4() + "    强弱："+epcInfo.getstr6()).append("\n");
                            }
                        }
                    }
                    setShowMsg("多余标签：" + str);
                }
			}

            int SS_size = scanStatementBeans.size();
            boolean isIdentical = false;
            for (int i = 0; i < SS_size; i++) {
                if (scanStatementBeans.get(i).getData() == size) {
                    isIdentical = true;
                    scanStatementBeans.get(i).setCount((scanStatementBeans.get(i).getCount() + 1));
                    break;
                }
            }
            //如果历史盘点中没有与之相对的数量,就是盘点出标签个数不同
            if (!isIdentical) {
                scanStatementBeans.add(new ScanStatementBean(size, 1));
            }

            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    adapter.notifyDataSetChanged();
                }
            },1);
        }
        catch (Exception e){
            setShowMsg("error:"+e);
        }
    }

    //盘点中返回
    @Override
    public void callback_Inventorying(final int ScanCount, final List<EPCInfo> dataTmp) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                test_LabelMsg_Tv.setText("标签数："+dataTmp.size()+",扫描次数："+ScanCount);
            }
        });
    }

    //盘点完成返回
    @Override
    public void callback_InventoryEnd(List<EPCInfo> dataTmp, long time) {
        stopScan();

        int size = dataTmp.size();
        final StringBuilder str = new StringBuilder();
        str.append("标签数："+size+"   耗时："+time);

        long startComparisonTime = System.currentTimeMillis();

        List<String> list = new ArrayList<String>();
        double strength = 0;//信号强度
        String strengtStr = "";//信号强度

        StringBuilder labelStr = new StringBuilder();//标签数据

        for (int i=0;i<size;i++) {
            list.add(dataTmp.get(i).getstrEpc());
            labelStr.append("Epc:" + dataTmp.get(i).getstrEpc() + "   Tid:" + dataTmp.get(i).getstrTid() + "\n");

            int strengthSzie = labelStrengths.size();
            boolean isExist = false;//是否存在此标签在数据
            try {
                strengtStr = dataTmp.get(i).getstr6();
                strength = Double.valueOf(strengtStr.substring(1,strengtStr.length()-3));
                if (strength >= 80.0) {
                    for (int z = 0; z < strengthSzie; z++) {
                        //信号强度数据
                        if (labelStrengths.get(z).getLabelStr().equals(dataTmp.get(i).getstrEpc())) {
                            labelStrengths.get(z).setLowCount((labelStrengths.get(z).getLowCount() + 1));

                            if (strength>labelStrengths.get(z).getLowStrength()){
                                labelStrengths.get(z).setLowStrength(strength);
                            }
                            isExist = true;
                            break;
                        }
                    }

                    if (!isExist) {
                        labelStrengths.add(new LabelStrength(dataTmp.get(i).getstrEpc(), strength, 0, 1));
                    }
                }

                //展示若标签数据
                labelStrengthAdapter.notifyDataSetChanged();
            }
            catch (Exception e){
                setShowMsg("统计弱信号标签错误："+e);
            }
        }

        setLabelData(size,list,dataTmp);

        str.append("    ComparisonTime："+(System.currentTimeMillis()-startComparisonTime)+"\n");
        str.append(labelStr);
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                test_LabelMsg_Tv.setText(str.toString());
            }
        },1);


        scanCount++;

        if (scanCount%1000==0 && scanCount!=0){
            scanCount = 0;
            intervalTime = 1000 * 60 * 60;
            setShowMsg("achieve count 1000,thread sleep");
        }
        else {
            intervalTime = 5000;
        }

        if (circulate){
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (circulate && isRun && !isScan) {
                        toScanLabel();
                    }
                }
            },intervalTime);
        }

    }

    //温感返回
    @Override
    public void callBackTemperature(double temperature, double humidity) {
        setShowMsg("温度："+temperature+"  湿度：" + humidity);
    }

    //锁板状态
    @Override
    public void callBackDoorStatus(final int status, final int type, final String msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                String str = "";
                if (status==1){
                    str = "锁起，门未开";
                }
                else if (status==2){
                    str = "锁起，门开";
                }
                else if (status == 0){
                    if (type==0){
                        str = "正常落锁";
                    }
                    else {
                        str = "超时未开门落锁";
                    }
                }
                doorStatus_Tv.setText(""+str+"   "+msg+"   "+status);
                setShowMsg(str);
            }
        });
    }

    //返回运行输出状态
    @Override
    public void callBackMsg(int status, String msg) {
        setShowMsg(msg);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        isRun = false;
        if (iLockControl!=null) {
            iLockControl.stop();
        }
        stopScan();
        CloseDev();
    }
}
